package top.chukongxiang.project.base.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class StreamUtils {

    public static byte[] readBytes(InputStream inputStream) throws IOException {
        if (inputStream==null) {
            return null;
        }
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024]; //buff用于存放循环读取的临时数据
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }


    public static ByteArrayInputStream bufferedImageToInputStream(BufferedImage image, String format){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, format, os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class TmpFile {

        public static final String prefix = "leader-";

        // 创建缓存文件，使用完成后注意删除
        public static File tmpByStream(InputStream ins) throws IOException {
            if (ins==null) {
                return null;
            }
            File tempFile;
            byte[] bytes = StreamUtils.readBytes(ins);

            tempFile = File.createTempFile(prefix,  null);
            FileUtils.writeFile(bytes, tempFile);

            return tempFile;
        }

        public static File tmpByStream(byte[] bytes) throws IOException {
            File tempFile = File.createTempFile(prefix,  null);
            FileOutputStream fileOutputStream = new FileOutputStream(tempFile);

            fileOutputStream.write(bytes);

            fileOutputStream.flush();
            fileOutputStream.close();
            return new File(tempFile.getCanonicalPath());

//            RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "rw");
//            FileChannel channel = randomAccessFile.getChannel();
//            ByteBuffer allocate = ByteBuffer.allocate(bytes.length);
//            allocate.flip();
//            channel.force(true);
//            channel.write(allocate);
//            channel.close();
//
//            allocate.clear();
//            randomAccessFile.close();
////            FileUtils.writeFile(bytes, tempFile);
//            return tempFile;
        }

    }

}
